const { DataTypes } = require('sequelize');

/**
 * 用户活跃度记录模型
 * @param {import('sequelize').Sequelize} sequelize Sequelize实例
 */
module.exports = (sequelize) => {
  const UserActivity = sequelize.define('UserActivity', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'users',
        key: 'id'
      }
    },
    date: {
      type: DataTypes.DATEONLY,
      allowNull: false
    },
    activeTime: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '活跃时间，单位为秒'
    },
    messagesSent: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '发送消息数量'
    },
    messagesReceived: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '接收消息数量'
    },
    averageResponseTime: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: '平均响应时间，单位为秒'
    },
    responseRate: {
      type: DataTypes.FLOAT,
      allowNull: true,
      comment: '响应率，0-1之间的小数'
    },
    contactCount: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '互动的联系人数量'
    },
    sessionStarts: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: 'WhatsApp会话开始次数'
    },
    loginTime: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '首次登录时间'
    },
    logoutTime: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '最后登出时间'
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false
    }
  }, {
    tableName: 'user_activities',
    timestamps: true,
    indexes: [
      {
        fields: ['userId']
      },
      {
        fields: ['date']
      },
      {
        unique: true,
        fields: ['userId', 'date']
      }
    ]
  });

  // 添加关联
  UserActivity.associate = (models) => {
    UserActivity.belongsTo(models.User, {
      foreignKey: 'userId',
      as: 'user'
    });
  };

  return UserActivity;
}; 